package edu.iscas.xcheck.analysis.service;

import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import edu.iscas.xcheck.utils.http.PostClient;

@Component
@ConfigurationProperties(prefix="xcheck")
public class RegisterClient {
	private static String host;
	private static String port;
	private static String path;
	private static String keepPath;
	private static String selfAddress;
	private static String selfPort;
	private static String postPath;
	private static Timer timer;

	public RegisterClient() {
	}
	private static Logger LOG = LoggerFactory.getLogger(RegisterClient.class); 
	
	public void sendClientInfo(){
		PostClient postClient = new PostClient(host, port, path);
		String[] names = {"Address", "Port"};
		String[] values = {selfAddress, selfPort};
		try{
			postClient.setJsonContent(names,values);
			String responseStr = postClient.sendRequest();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	private void keepClient(){
		PostClient postClient = new PostClient(host, port, keepPath);
		String[] names = {"Address", "Port"};
		String[] values = {selfAddress, selfPort};
		postClient.setJsonContent(names, values);
		try {
			String responseStr = postClient.sendRequest();
			LOG.debug(responseStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@PostConstruct
	public void regClient(){
		sendClientInfo();
		startThread();
	}
	
	private void startThread(){
		this.timer = new Timer();
		this.timer.scheduleAtFixedRate(new TimerTask(){
			@Override
			public void run() {
				keepClient();
			}
		}, 0, 10000);
	}
	
	public static String getHost() {
		return host;
	}
	public static void setHost(String host) {
		RegisterClient.host = host;
	}
	public static String getPort() {
		return port;
	}
	public static void setPort(String port) {
		RegisterClient.port = port;
	}
	public static String getPath() {
		return path;
	}
	public static void setPath(String path) {
		RegisterClient.path = path;
	}
	public static String getSelfAddress() {
		return selfAddress;
	}
	public static void setSelfAddress(String selfAddress) {
		RegisterClient.selfAddress = selfAddress;
	}
	public static String getSelfPort() {
		return selfPort;
	}
	public static void setSelfPort(String selfPort) {
		RegisterClient.selfPort = selfPort;
	}
	public static String getPostPath() {
		return postPath;
	}
	public static void setPostPath(String postPath) {
		RegisterClient.postPath = postPath;
	}
	public static String getKeepPath() {
		return keepPath;
	}
	public static void setKeepPath(String keepPath) {
		RegisterClient.keepPath = keepPath;
	}
	
}
